

const config = require('./config');

const path = require('path');

const citiesFileName = path.join(process.cwd(), 'cities.json');

/**
 * 抓取美团上城市数据
 */


function getAreaAndCities($) {

    let cities = new Map();

    $('.city-list').children('div').each((i, element) => {

        let areaName = $(element).children('h3').first().text();

        let cityNames = [];

        $(element).children('a').contents().each((j, data) => {

            $(data.parent).attr('href')

            cityNames.push({ cityName: data.data, href: $(data.parent).attr('href') });

        });

        cities.set(areaName, cityNames);
    });
    return cities;
}

function getCities($) {
    let cities = new Array(); 
    
    let citiesMap = new Map();

    $('.city-list').children('div').children('a').contents().each((i, element) => {

        let city = queryCityByName(element.data);

        if (city && city.id) {

            let data = { cityName: element.data, url: 'http://' + path.join(config.spiderHost, $(element.parent).attr('href')), cityId: city.id };

            cities.push(data);

            citiesMap.set(data.url, { cityName: data.cityName, cityId: data.cityId });
        }
    });
    return { cities, citiesMap };
}

function queryCityByName(cityName) {
    var city = Object.create(null);

    let cityDatas = require(citiesFileName);

    cityDatas.forEach(function (element) { 

        if (element.name.indexOf(cityName) != -1) {
            city = element;
        }
    }, this);

    return city;
}


module.exports = {
    getCities,
    getAreaAndCities
}